<template>
  <el-upload
    class="upload-demo"
    :action="uploadUrl"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :on-exceed="handleExceed"
    :file-list="fileList"
    list-type="picture"
    :limit="limit"
  >
    <el-button
      size="small"
      type="primary"
    >点击上传</el-button>
    <!-- <div slot="tip" class="el-upload__tip">请上传图片</div> -->
  </el-upload>
</template>

<script>
  
export default {
  name: 'ImageUpload',
  props: {
    // eslint-disable-next-line vue/require-default-prop
    fileList: Array,
    // eslint-disable-next-line vue/require-default-prop
    field: String,
    // eslint-disable-next-line vue/require-default-prop
    limit: Number
  },
  data() {
    return {
      uploadUrl: [process.env.VUE_APP_BASE_API] + `/api/upload/image`
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.emitFileList(fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(file, fileList) {
      this.$message('超出上传数量限制，可以先删除再上传！')
    },
    handleSuccess(response, file, fileList) {
      this.emitFileList(fileList)
    },
    emitFileList(fileList) {
      const emit_fileList = []
      fileList.forEach(element => {
        if (element.response !== null && element.response !== undefined) {
          const file = {
            name: element.response.data.file_name
          }
          emit_fileList.push(file)
        } else {
          const file = {
            name: element.name
          }
          emit_fileList.push(file)
        }
      })
      this.$emit('fileListChange', { field: this.field, fileList: emit_fileList })
    }
  }
}
</script>

<style>
.el-upload-list--picture .el-upload-list__item-thumbnail {
  width: auto;
}
</style>
